package com.wmz.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wmz.config.WhiteUrlsConfig;
import com.wmz.constant.AuthConstants;
import com.wmz.constant.BusinessEnum;
import com.wmz.constant.HttpConstants;
import com.wmz.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * @author wmz
 * @date 2024/6/30 22:52
 * @description 校验请求的合法性，拦截非法请求。
 * 前提：
 *  前后端约定好token存放位置
 *  存放在请求头header中的Authorization: Bearer 【Token】
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private WhiteUrlsConfig whiteUrlsConfig;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径
        String path = request.getPath().toString();
        // 判断请求是否在白名单中
        if(whiteUrlsConfig.getAllowUrls().contains(path)) {
            // 在白名单中，放行
            return chain.filter(exchange);
        }
        // 请求不在白名单中，校验token
        // 判断请求头中的AUTHORIZATION的值
        String authorizationValue  = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        if(StringUtils.hasText(authorizationValue)) {
            // 获取token
            String token = authorizationValue.replaceFirst(AuthConstants.BEARER,"");
            // 校验token是否合法：1.有值 2.存在redis中
            if(StringUtils.hasText(token) &&
                    stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + token)) {
                // token合法，放行
                return chain.filter(exchange);
            }
        }
        // token不合法，拦截请求，返回响应处理
        log.error("非法请求，请求路径：{}，拦截时间：{}",path,new Date());
        // 拦截请求，返回响应处理
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应头，响应内容格式为json
        response.getHeaders().set(HttpConstants.CONTENT_TYPE, HttpConstants.APPLICATION_JSON);
        // 创建响应结果，由于请求路径中的请求头未携带token即用户验证失败，响应码为401
        Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZAION);
        // 用于将一个对象转换成byte数组
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes =  objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return -5;
    }
}
